const express = require('express');
const router = express.Router();
const { login } = require('../controller/login')
const { SuccessModel, ErrorModel } = require('../model/resModel')


router.get('/', function (req, res) {
    res.render('login', {title: '登录'})
});

router.post('/in', (req, res, next) => {
    const { username, password } = req.body;
    const result = login(username, password);
    return result.then(data => {
        if (data.username) {
            // 设置 session
            req.session.username = data.username;
            req.session.realname = data.realname;
            req.session.role     = data.name;

            res.json(
                new SuccessModel({
                    role: data.name
                })
            );
            return
        }
        res.json(
            new ErrorModel('登录失败')
        )
    })
});

module.exports = router;